<script lang="ts">
	import { Tooltip } from 'flowbite-svelte'
	import type { Table as FudaTable } from './bindings/Table'
	import {
		Table,
		TableBody,
		TableBodyCell,
		TableBodyRow,
		TableHead,
		TableHeadCell,
		Checkbox,
		TableSearch,
	} from 'flowbite-svelte'
	import { onMount } from 'svelte'
	import * as commands from '$lib/commands'
	import type { Column } from './bindings/Column'
	import type { UpdateParams } from './bindings/UpdateParams'

	let klineFlatTable: FudaTable | null = null // Initialize as null

	onMount(async () => {
		try {
			const res = await commands.get_kline_flat_table()
			console.log('(get_kline_flat_table) ipcResponse ', res)
			if (res.error) {
				throw new Error(`(SecuritySetting)Server returned an error: ${res.error}`)
			}
			klineFlatTable = res.result?.data ?? null // Assign the result or null if undefined
		} catch (error) {
			// Handle fetch errors here
			console.error('Error fetching data:', error)
		}
	})

	async function handleCheckboxChange(event: Event, column: Column) {
		// Cast event.target to HTMLInputElement to access the 'checked' property
		const checkbox = event.target as HTMLInputElement
		// Directly update the column visibility based on the event
		column.visible = checkbox.checked
		// Call your API to update visibility
		let args: UpdateParams<Column> = {
			id: column.id?.id.String,
			data: column,
		}
		try {
			await commands.update_kline_flat_table_column(args)
			// Optionally, handle success response here
			console.log(
				`(handleCheckboxChange) Column visibility for ID ${column.id} updated successfully.`,
			)
		} catch (error) {
			// Handle any errors that occur during the API call
			console.error(
				`(handleCheckboxChange) Failed to update column visibility for ID ${column.id}:`,
				error,
			)
		}
	}
</script>

<Table hoverable={true}>
	<TableHead defaultRow={false}>
		<tr
			class="bg-gray-400 text-center text-xs font-medium text-gray-900 uppercase sticky top-0 z-10"
		>
			<TableHeadCell padding="p-0" class="text-nowrap">显示</TableHeadCell>
			<Tooltip arrow={false} placement="top">Signal</Tooltip>
			<TableHeadCell padding="p-0" class="text-nowrap sticky left-0 top-0 bg-gray-400">
				Name
			</TableHeadCell>

			<TableHeadCell padding="p-0" class="text-nowrap">标题</TableHeadCell>
			<Tooltip arrow={false} placement="top">Signal</Tooltip>
		</tr>
	</TableHead>
	<TableBody tableBodyClass="divide divide-solid divide-green-200 text-xs text-gray-500">
		{#if klineFlatTable && klineFlatTable.columns && klineFlatTable.columns.length > 0}
			<!-- Add a guard clause -->
			{#each klineFlatTable.columns as column, index (column.id)}
				<TableBodyRow class="hover:bg-blue-300 focus-within:bg-blue-500 bg-gray-200">
					<TableHeadCell class="!p-4">
						<Checkbox
							checked={column.visible ?? false}
							on:change={(event) => handleCheckboxChange(event, column)}
						/>
					</TableHeadCell>
					<TableBodyCell
						tdClass="pr-1"
						class="text-xs font-medium text-gray-900 whitespace-nowrap sticky left-0 bg-gray-200"
					>
						{column.name}
					</TableBodyCell>

					<TableBodyCell tdClass="pr-1">{column.title}</TableBodyCell>
				</TableBodyRow>
			{/each}
		{/if}
	</TableBody>
</Table>
